// pages/my/IsDealerOrder.js
var wxpay = require('../../utils/pay.js')
var app = getApp()
Page({
  data: {
    statusType: ["订单","售后"],
    currentType: 0,
    tabClass: ["", "", "", "", ""],
    bodyHeight:null,
    index:1,
    isFinish:false,
    orderList:[],
    selectIndex: 0,
    hideShopPopup: true,
    standardList: [],
    changeIdx: 0,
    standardPrice: 0,
    newStandard: null,
    items: [
      {value: 1, name: '微信支付', checked: 'true'},
      {value: 2, name: '对公账号'}
    ],
    payType:1,
    isShowPayType:false,
    order:{},
  },
  showPayTypeBox(e){
     this.setData({
      isShowPayType:true,
      selectIndex: e.currentTarget.dataset.idx,
      order:e.currentTarget.dataset.it
    })
  },
  togglePayTypeBox(){
    this.setData({
      isShowPayType:!this.data.isShowPayType
    })
  },
  radioChange(e){    
    this.setData({
      payType:e.detail.value
    })
  },
  statusTap: function (e) {
    console.log(e);
    console.log(e.hasOwnProperty("currentTarget"))
    if(e&&e.hasOwnProperty("currentTarget")){
        this.setData({
          currentType: e.currentTarget.dataset.index
        });
    }else{
      this.setData({
        currentType: e.currentType
      });
    }   
    this.setData({
      orderList:[],
      isFinish:false,
      index:1,
    })
    this.getData();
    // this.onShow();
  },
  orderDetail: function (e) {
    var orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/order-detail/order-detail?id=" + orderId + '&share=1'
    })
  },
  cancelOrderTap: function (e) {
    var that = this;
    var orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确定要取消该订单吗？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading(           {
            title: '加载中...',
            mask: true});
          app.postForm("/order/cancel_order",{
            CustId:app.globalData.uid,
            OrderId:orderId
          },res=>{
            wx.hideLoading();
            if(res&&res.code=="0"){
              that.statusTap({currentType:0});   
            }
          })
        }
      }
    })
  },

  showPop(e){
    let stand = e.currentTarget.dataset.stand
    var childs =  this.data.goodsList[0].standard
    childs.forEach( item => {
      item.active = false
    })
    if(stand){
      for (var i = 0; i < childs.length; i++) {
        if( childs[i].Id == stand.Id ){
          childs[i].active = true
        }
      }
    }else{
      childs[0].active = true
    }
    this.data.goodsList[0].standard = childs
    // childs[0].active = true
    this.setData({
      hideShopPopup: false,
      standardPrice: this.data.goodsList[0].standard[0].Price,
      goodsList: this.data.goodsList
    })
  },

  dealerPay(){
    let that = this
    let standardList = that.data.standardList
    let stand = that.data.orderList[that.data.changeIdx].Detail[0]
    var standardPrice = that.data.standardPrice
    standardList.forEach( item => {
      item.active = false
    })
    for (var i = 0; i < standardList.length; i++) {
      if( standardList[i].Id == stand.StandardId ){
        standardList[i].active = true
        standardPrice = standardList[i].Price * standardList[i].MinBuy
      }
    }
    that.setData({
      hideShopPopup: false,
      standardPrice
    })
    this.setData({
      standardList,
    })
    wx.hideLoading({
      success: (res) => {},
    })
    // this.labelItemTap()
  },
  labelItemTap(e){
    var that = this
    let standardList = that.data.standardList
    console.log(e)
    let i =  e && e.hasOwnProperty("currentTarget") ? e.currentTarget.dataset.propertyindex : 0
    let detail = that.data.orderList[that.data.changeIdx].Detail[0]
    standardList.forEach( item => {
      item.active = false
    })
    detail.StandardName = standardList[i].Name
    detail.Num = standardList[i].MinBuy
    console.log(that.data.orderList[that.data.changeIdx])
    that.data.orderList[that.data.changeIdx].Total = standardList[i].Price * standardList[i].MinBuy
    standardList[i].active = true
    that.data.newStandard = standardList[i]
    that.data.newStandard.Num = that.data.newStandard.MinBuy
    that.setData({
      standardPrice: standardList[i].Price * standardList[i].MinBuy,
      standardList,
      orderList: that.data.orderList
    })
    let postData = {
      OrderId: that.data.orderList[that.data.changeIdx].OrderId,
      StandardId: detail.StandardId,
      NewStandard: JSON.stringify(that.data.newStandard)
    }
    app.postForm('order/update_order_detail_standard_by_orderid', postData, res => {
      console.log(res)
      if( res.code == 0 ){
        detail.StandardId = that.data.newStandard.Id
      }
    })
  },
  buyNow(){
    let that = this
    var orderId = that.data.orderList[that.data.changeIdx].OrderId
    let orderList = that.data.orderList
    orderList[that.data.changeIdx].Status = 99

    that.setData({
      orderList
    })
    let payData = {
      OrderIds: orderId,
      OpenId: app.globalData.openid,
      Type: 'JSAPI'
    }
    app.postForm('order/pay_order_by_orderids', payData, rep => {
      console.log(rep)
      wx.hideLoading();
      that.wxPay(rep)
    })
  },
  toPayTap: function (e) {
    wx.showLoading(           {
      title: '加载中...',
      mask: true});
    var that = this;
    this.setData({
      isShowPayType:false
    })
    if( e.currentTarget.dataset.type == 2 ){
      wx.showToast({
        title: '财务正在核对支付状态，请等待',
        icon: 'none'
      })
      return
    }
    var orderId = e.currentTarget.dataset.id;
    var money = e.currentTarget.dataset.money;
    let orderList = that.data.orderList

    orderList[that.data.selectIndex].Status = 99
    that.setData({
      orderList
    })
    if( that.data.payType == 2 ){
      let postData = {
        PayType: that.data.payType,
        OrderId: orderId
      }
      app.postForm('order/update_order_paytype_by_orderid', postData, res => {
        if( res && res.code == 0 ){
          wx.showToast({
            title: '订单已提交',
            icon: 'success',
            duration: 1000,
            success: () => {
              setTimeout(function () {
                wx.navigateBack({
                  delta: 1 //返回上一级页面
                })
              }, 1000)
            }
          })
        }
      })
    }else{
      let payData = {
        OrderIds: orderId,
        OpenId: app.globalData.openid,
        Type: 'JSAPI'
      }      
      app.postForm('order/pay_order_by_orderids', payData, rep => {
        // console.log(rep)
        wx.hideLoading();
        that.wxPay(rep)
      })
    }       
  },
  wxPay(params) {
    let that = this        
    let orderList = that.data.orderList
    setTimeout(this.checkOrder,3000);
    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: 'MD5',
      paySign: params.paySign,
      success: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '支付成功',
          icon: 'success'
        })
        orderList[that.data.selectIndex].Status = 1
        that.setData({
          orderList,
          hideShopPopup: true
        })
        that.statusTap({currentType:0})        
        wx.switchTab({
          url: '/pages/d-center/list',
        })
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '已取消支付',
          icon: 'none'
        })
        orderList[that.data.selectIndex].Status = 0
        that.setData({
          orderList,
          hideShopPopup: true
        })

      },
      complete: function (res) {
        wx.hideLoading();

      }
    })
  },
  checkOrder(){
    wx.showLoading({
      title: 'title',
      mask:true
    })    
    console.log(this.data.order);
    app.get("order/get_order_by_orderid?OrderId="+this.data.order.OrderId,res=>{
      wx.hideLoading({
        success: (res) => {},
      })
      console.log(res);
      if(res&&res.code=='0'){
        if(res.result.Status==1){
          wx.switchTab({
            url: '/pages/d-center/list',
          })
        }
      }
    })
  },
  closePopupTap: function () {
    this.setData({
      hideShopPopup: true
    })
  },
  onLoad: function (e) {
    var that = this;
    wx.hideShareMenu()
    var currentType;
    if(e&&e.hasOwnProperty('share')){
      if (e.share) {
        that.setData({ share: e.share });
        currentType = e.currentType;
      }
    }
    if (app.globalData.iphone == true) { that.setData({ iphone: 'iphone' }) }

    this.data.currentType = currentType;
    if (currentType) {
      that.setData({
        currentType: currentType
      });
    }
    console.log(e)
  },
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成

  },
  getOrderStatistics: function () {
    var that = this;    
  },
  refund(e){
    let OrderId = e.currentTarget.dataset.id
    let that = this
    wx.showModal({
      title: '提醒',
      content: '退款申请操作不可逆，是否确认退款？',
      confirmColor: '#008B8B',
      success: res => {
        wx.showLoading({
          title: '退款中...',
          mask: 'true'
        })
        if( res.confirm ){
          app.postForm('order/refund_order', {
            CustId: app.globalData.uid,
            OrderId,
          }, res => {
            wx.hideLoading()
            if( res.code == 0 ){
              wx.showToast({
                title: '退款申请已提交',
              })
              that.statusTap({currentType:0});   
            }
          })
        }
      }
    })
  },
	toConfirmTap:function(e){
	  let that = this;
	  let orderId = e.currentTarget.dataset.id;
	  let formId = e.detail.formId;
	  wx.showModal({
	      title: '确认您已收到商品？',
	      content: '',
	      success: function(res) {
	        if (res.confirm) {
	          wx.showLoading(           {
              title: '加载中...',
              mask: true});
	          app.postForm("/order/receive_order",{
              CustId:app.globalData.uid,
              OrderId:orderId
            },res=>{
              wx.hideLoading({
                success: (res) => {},
              })
              if(res&&res.code=='0'){
                that.statusTap({currentType:2});   
              }
            })
	        }
	      }
	  })
  },
  logisticsTap(e){
    var orderId=e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/logistics/logistics?id='+orderId,
    })
  },
  getData:function(status,index){
    let _this=this;
    if(this.data.isFinish){
      // wx.showToast({
      //   title: '没有更多了~',
      // })
      return
    }
    let sta='s4';
    if(this.data.currentType==1){
      sta='s2'
    }
    wx.showLoading({
      title: '加载中...',
      mask:true
    })    
    app.get(`order/get_orders?CustId=${app.globalData.uid}&page=${this.data.index}&size=20&IsDealer=1&Status=${sta}`,(res)=>{
      wx.hideLoading();
      if(res&&res.code=="0"){
        if(res.result.length>0){
          // res.result[0].Status = 0
          _this.setData({
            orderList:_this.data.orderList.concat(res.result),
            index:this.data.index+1
          });
        }else{          
          _this.setData({
            isFinish:true,
          })
          // wx.showToast({
          //   title: '没有更多了~',
          // })
        } 
      }
    })
  },
  onShow: function (e) {
    // 获取订单列表
    // wx.showLoading();
    var that = this;
    var postData = {
      token: app.globalData.token
    };
    this.setData({
      isFinish: false,
      orderList: [],
      index: 1
    })
    that.getData()
    postData.status = that.data.currentType;
    app.get('goods/get_dealer_goods_info', res => {
      console.log(res)
      res.standard.forEach( item => {
        item.active = false
      })
      that.setData({
        standardList: res.standard
      })
    })
    // this.getOrderStatistics();

    // wx.request({
    //   url: app.siteInfo.url + app.siteInfo.subDomain + '/order/list',
    //   data: postData,
    //   success: (res) => {
		// 		console.log(res)
    //     wx.hideLoading();
    //     if (res.data.code == 0) {
    //       that.setData({
    //         orderList: res.data.data.orderList,
    //         logisticsMap: res.data.data.logisticsMap,
    //         goodsMap: res.data.data.goodsMap
    //       });
    //     } else {
    //       this.setData({
    //         orderList: null,
    //         logisticsMap: {},
    //         goodsMap: {}
    //       });
    //     }
    //   }
    // })
		// var winInfo = wx.getSystemInfo({
		// 	success: function (res) {
		// 		var windowHeight = res.windowHeight;
		// 		var statusBarHeight = res.statusBarHeight;
		// 		var titleBarHeight = 0
		// 		if (res.model.indexOf('iPhone') !== -1) {
		// 			titleBarHeight = 44
		// 		} else {
		// 			titleBarHeight = 48
		// 		}
		// 		var query = wx.createSelectorQuery();
		// 		query.select('.status-box').boundingClientRect()
		// 		query.exec((res) => {
		// 		  var listHeight = res[0].height; // 获取list高度
		// 			that.setData({ bodyHeight: windowHeight - statusBarHeight - titleBarHeight - listHeight });
		// 		})
				
			
		// 	}
		// });
  },
  onHide: function () {
    // 生命周期函数--监听页面隐藏

  },
  onUnload: function () {
    // 生命周期函数--监听页面卸载

  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作

  },
  onReachBottom: function () {
    // 页面上拉触底事件的处理函数

  }
})